package com.payne;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.UUID;

public class ZolSpider2 implements PageProcessor {


    private Site site=Site.me()
            .setUserAgent("User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50")
            .setRetryTimes(3)
            .setSleepTime(3000);

    private static String url="http://desk.zol.com.cn/";


    public void process(Page page) {
        if(url.equals(page.getUrl().toString())){
            List<String> all = page.getHtml().xpath("//ul[@class=\"pic-list2 clearfix\"]/li/a/@href").all();
            for (String s : all) {
                //http://desk.zol.com.cn/bizhi/5132_63536_2.html
                ///bizhi/7498_92909_2.html
                s="http://desk.zol.com.cn"+s;

            }
            page.addTargetRequests(all);
        }else {
            String s = page.getHtml().xpath("//*[@id=\"bigImg\"]/@src").get();
            try {
                if(s.startsWith("h")){
                    URL url = new URL(s);
                    URLConnection conn = url.openConnection();
                    InputStream inputStream = conn.getInputStream();
                    byte[] buf=new byte[1024];
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    int len;
                    while ((len=inputStream.read(buf))!=-1){
                        byteArrayOutputStream.write(buf,0,len);

                    }
                    inputStream.close();
                    byteArrayOutputStream.close();
                    String uuid = UUID.randomUUID().toString();
                    //f://test//"+uuid+".jpg
                    //File file = new File("F:/test/" + uuid + ".jpg");
                    File file = new File("f://test//"+uuid+".jpg");
                    FileOutputStream fileOutputStream=new FileOutputStream(file);
                    fileOutputStream.write(byteArrayOutputStream.toByteArray());
                    fileOutputStream.close();


                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new ZolSpider2()).addUrl(url).thread(5).run();
    }

}
